<template>
  <ul class="ee-pagination">
    <li v-for="item in _items" :disabled="item.disabled" :aria-current="item.page == modelValue">
      <slot :name="item.name || item.page">
        <ee-shape v-if="item.shape" :shape="item.shape"></ee-shape>
        <template v-else>
          {{ item.page }}
        </template>
      </slot>
    </li>
  </ul>
</template>

<script type="text/javascript">
import { injectStore } from 'ee-vuex'

export default injectStore({
  name: "ee-pagination",
  data() {
    return {
    }
  },
  emits: {
    /** 当前页发生变化时触发
     * @param {number} value - 当前页
     */
    onChange: (value) => true,
  },
  props: {
    /** 当前页码，从 1 开始 */
    modelValue: {
      init: 1,
      set(value) {
        if (value < 1)
          value = 1;
        if (value > this.pages)
          value = this.pages;
        this.$emit("change", value, this);
        return value;
      }
    },
    /** 总页数 */
    page: Number,
    /** 翻页按钮的数量 */
    button: {
      type: Number,
      default: 11,
    },
    /** 每页条数 */
    count: {
      type: Number,
      default: 20,
    },
    /** 总条数 */
    total: Number,
    /** 页码按钮是否显示背景 */
    background: Boolean,

    onChange: {
      type: Function,
      /** */
      default: undefined,
    },
  },
  computed: {
    /** 总页数 */
    pages() {
      if (this.page)
        return this.page;
      return ((this.total - 1) / this.count | 0);
    },
    /** 翻页的按钮内容 */
    _items() {
      const items = [];
      const value = this.modelValue;
      const button = this.button;
      const pages = this.pages;
      items.push({ name: 'prev', shape: 'left', page: value - 1, disabled: value <= 1, });

      let start = value - ((button - items.length) / 2) | 0;
      if (start > 1) {
        items.push({ name: '1', page: 1 });
        if (start > 2)
          items.push({ page: pages, text: ['···', '>>'] });
      }
      else
        start = 1;

      while (true) {
        items.push({ page: start });
        start++;
        if (start >= pages)
          break;
      }

      return items;
    },
  },
  mounted() {
  },
})
</script>

<style lang="scss" scoped>
.ee-pagination {
  display: flex;
  gap: .5em;
  color: #333;

  li {
    padding: 0 .25em;
    min-width: 2em;
    line-height: 2;
    cursor: pointer;
    display: flex;
    justify-content: center;
    background-color: #f2f2f2;
    border-radius: var(--ee-border-radius);
  }
}
</style>